package cn.dinkevin.xui.watcher;

import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * 输入框长度监听
 * Created by ChengPengFei on 2017/2/13 0013.</br>
 * Copyright ©2017 juziwl, All Rights Reserved.
 */

public class EditTextLengthWatcher implements TextWatcher{

    private int maxLength;          // 最大长度
    private EditText edt_input;     // 输入框

    /**
     * EditText 输入长度变化监听
     */
    public interface InputCallback {

        /**
         * 内容长度变化回调
         * @param content 内容
         * @param length 长度
         */
        void onInputContentChanged(String content, int length);
    }
    protected InputCallback lengthWatcher;

    /**
     * 构造器
     * @param edt_input 输入框
     * @param maxLength 最大长度
     */
    public EditTextLengthWatcher(EditText edt_input, int maxLength, InputCallback callback){
        this.edt_input = edt_input;
        this.maxLength = maxLength;
        this.edt_input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
        this.lengthWatcher = callback;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable s) {
        int length = edt_input.length();
        if(null != lengthWatcher)
            lengthWatcher.onInputContentChanged(edt_input.getText().toString(),length);
    }
}
